<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/gmxs/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/gmxs/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/gmxs/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/gmxs/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/gmxs/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/gmxs/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/gmxs/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="java," />





  <link rel="alternate" href="/gmxs/atom.xml" title="葛木小舍先生的博客" type="application/atom+xml" />






<meta name="description" content="本篇博文就Java语言的一些基本元素进行一些记录和阐述，主要讲解一下Java语言的一些基本构成元素和Java的主类结构。">
<meta name="keywords" content="java">
<meta property="og:type" content="article">
<meta property="og:title" content="java语言基础">
<meta property="og:url" content="http://yoursite.com/2019/04/01/java初探/JAVA语言基础/index.html">
<meta property="og:site_name" content="葛木小舍先生的博客">
<meta property="og:description" content="本篇博文就Java语言的一些基本元素进行一些记录和阐述，主要讲解一下Java语言的一些基本构成元素和Java的主类结构。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/8067684-618a2a53e86594e0.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/8067684-a24cbcb6ed77190f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/8067684-b1a4618f1cdaa642.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/8067684-92779cb6c0ba9feb.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/8067684-c80b044d8d73228b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/8067684-f0a19c0aef1e07e6.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/8067684-945342cce57e417b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/8067684-01f69c794db5c146.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/8067684-94be843e28806342.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/8067684-9260a0313629104f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/8067684-8cafab8620d9d0de.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/8067684-4ef63c0d9b08b6f0.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/8067684-a3c6c7827f85df27.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/8067684-626779d391653b0c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:updated_time" content="2020-04-14T07:23:15.982Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="java语言基础">
<meta name="twitter:description" content="本篇博文就Java语言的一些基本元素进行一些记录和阐述，主要讲解一下Java语言的一些基本构成元素和Java的主类结构。">
<meta name="twitter:image" content="https://upload-images.jianshu.io/upload_images/8067684-618a2a53e86594e0.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/gmxs/',
    scheme: 'Mist',
    version: '5.1.4',
    sidebar: {"position":"right","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2019/04/01/java初探/JAVA语言基础/"/>





  <title>java语言基础 | 葛木小舍先生的博客</title>
  









  
  <script type="text/javascript"
  color="0,0,255" opacity='0.7' zIndex="-2" count="99" src="//cdn.bootcss.com/canvas-nest.js/1.0.0/canvas-nest.min.js"></script>
  

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-right page-post-detail">
    <div class="headband"></div>


	<a href="https://your-url" class="github-corner" aria-label="View source on Github"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#70B7FD; color:#fff; position: absolute; top: 0; border: 0; left: 0; transform: scale(-1, 1);" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/gmxs/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">葛木小舍先生的博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/gmxs/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/gmxs/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/gmxs/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/gmxs/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/gmxs/2019/04/01/java初探/JAVA语言基础/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="葛木小舍先生">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/gmxs/images/touxiang.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="葛木小舍先生的博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">java语言基础</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-04-01T00:00:00+08:00">
                2019-04-01
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/gmxs/categories/java初探/" itemprop="url" rel="index">
                    <span itemprop="name">java初探</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/gmxs/2019/04/01/java初探/JAVA语言基础/" class="leancloud_visitors" data-flag-title="java语言基础">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">热度&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
			 <span>℃</span>
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  3,606
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  13
                </span>
              
            </div>
          

          
              <div class="post-description">
                  本篇博文就Java语言的一些基本元素进行一些记录和阐述，主要讲解一下Java语言的一些基本构成元素和Java的主类结构。
              </div>
          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <blockquote>
<p>本篇博文就Java语言的一些基本元素进行一些记录和阐述，主要讲解一下Java语言的一些基本构成元素和Java的主类结构。</p>
</blockquote>
<h2 id="Java语言基础的大致组成"><a href="#Java语言基础的大致组成" class="headerlink" title="Java语言基础的大致组成"></a>Java语言基础的大致组成</h2><hr>
<ol>
<li>java主类结构</li>
<li>基本的数据类型</li>
<li>变量与常量</li>
<li>运算符</li>
<li>数据类型的转换</li>
</ol>
<hr>
<ul>
<li>###Java主类结构。<blockquote>
<p>Java语言是面向对象的程序设计语言，Java程序的基本组成单元就是类。类体中又包括属性和方法两部分，每个Java程序都必须包含一个main()主方法，含有main()方法的类称为主类，只有主类中的main()主方法能够运行，其他类和其他方法只能在主方法中被调用，为主方法服务，如果一个类没有被主类，主方法用到，那么这个类在当前程序中就暂时是无用的。</p>
</blockquote>
</li>
</ul>
<p>Java主类的结构如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">public class class_structure &#123;  // 主类</span><br><span class="line">    public static void main(String[] args) &#123;  // 主方法。</span><br><span class="line">        </span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>main()方法是类体中的主方法，由{}括号开始与结束，public，static，void分别是main()方法的权限修饰符，静态修饰符，返回值修饰符。Java程序中的main()方法必须声明为public static void 。 String[] args 是一个字符串类型的数组，它是main()方法的参数，卖main()方法是程序执行的开始位置。</p>
<ul>
<li><strong>api类库</strong><br>在Java语言中可以通过import关键字导入相关的类。在jdk的api（应用程序接口）中提供了130多个包。可以通过api文档查看这些类，其中主要包括了类的继承结构，类的应用，成员变量表，构造方法等。并对每个变量的使用目的做了详细的描述，api文档是开发人员不可或缺的工具。</li>
</ul>
</blockquote>
<hr>
<ul>
<li><p>###基本数据类型<br><strong>在Java中有八种基本的数据类型来存储数值，字符和布尔值。</strong><br><img src="https://upload-images.jianshu.io/upload_images/8067684-618a2a53e86594e0.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="2019-3-30-01.png"></p>
</li>
<li><p><strong>整数类型</strong></p>
<blockquote>
<p>整数类型用来储存整数数值，既没有小数部分的数值。可以正负数。整型数据在Java程序中有三种表现形式，十进制，八进制，十六进制。</p>
</blockquote>
</li>
</ul>
<p>整数类型根据内存占用大小，分为byte，short，int，long 4种类型。他们具有不同的取值范围：</p>
<p><img src="https://upload-images.jianshu.io/upload_images/8067684-a24cbcb6ed77190f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="2019-3-30-02.png"></p>
<ul>
<li><strong>浮点类型</strong><blockquote>
<p>浮点类型表示有小数部分的数字，<strong>Java语言中浮点类型分为单精度浮点类型（flaot）和双精度浮点类型（double）</strong>，他们具有不同的取值范围。</p>
</blockquote>
</li>
</ul>
<p>单精度与双精度的根本区别就是小数后精确位数的多少，以及内存的占用。高精度的double型比单精度的float型精度高，但占用内存大。所以float与double的选择是根据使用的实际需求来确定的。<br><img src="https://upload-images.jianshu.io/upload_images/8067684-b1a4618f1cdaa642.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="2019-3-30-03.png"></p>
<p>在默认情况下，小数都被看做double型，若使用float型小数，则需要在小数后面添加F或f。在使用double型小数时也可以在后面加D或d来进行识别，不加也不会出错，但在使用float型小数时必须在后面加f或F。</p>
<ul>
<li><p><strong>字符类型</strong></p>
<blockquote>
<p><strong>字符类型（char）用于储存单个字符，占用16位（字节）的内存。</strong>在定义字符型变量时，要以单引号表示，双引号表示字符串，”s”，表示一个字符串，’s’表示一个字符。</p>
</blockquote>
<ul>
<li>转义字符<blockquote>
<p>转义字符是一种特殊的字符变量，它以\开头，后跟字符。转义字符具有特殊的含义，不同于字符原有的意义：<br><img src="https://upload-images.jianshu.io/upload_images/8067684-92779cb6c0ba9feb.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="2019-3-30-04.png"></p>
</blockquote>
</li>
</ul>
</li>
</ul>
<p>转义字符赋值给变量时，与字符常量值一样需要使用单引号。</p>
<ul>
<li><strong>布尔类型</strong><blockquote>
<p>布尔类型又称为逻辑类型，通过关键字Boolean来定义布尔类型变量。只有true和false两个值。分别代表布尔逻辑中的真和假。布尔值是不能和整数类型进行转换的，布尔类型通常被用作在流程控制中的判断条件。</p>
</blockquote>
</li>
</ul>
<hr>
<p>更新时间：<br>2019-3-30 2:00</p>
<hr>
<ul>
<li>###变量与常量<br>在学习变量与常量的定义之前，我们首先应当了解一下标识符个关键字，这对我们在定义变量的过程中会有所帮助。</li>
</ul>
<hr>
<ul>
<li><strong>标识符和关键字</strong></li>
<li>标识符<blockquote>
<p>标识符可以简单的理解为一个名字，用来标识类名，变量名方法名，数组名，文件名的有效字符序列。</p>
</blockquote>
</li>
</ul>
<p><strong>Java语言规定标识符由任意顺序的字母，下划线，美元符号和数字组成，并且第一个字符不能是数字。标识符不能是Java中的保留关键字</strong></p>
<p>另外需要注意的是，在Java语言中标识符是严格区分大小写的，且Java语言使用的是unicode标准字符集，最多可以识别65535个字符。</p>
<ul>
<li>关键字<blockquote>
<p>关键字是Java语言中已经被赋予了特定意义的一些单词，不可以把这些关键字当作标识符来使用，Java关键字如下图：</p>
</blockquote>
</li>
</ul>
<p><img src="https://upload-images.jianshu.io/upload_images/8067684-c80b044d8d73228b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="2019-4-1-12.png"></p>
<hr>
<ul>
<li><strong>变量的声明</strong></li>
</ul>
<blockquote>
<p>变量的使用是程序设计中的一个十分重要的环节，定义变量，就是告诉编译器这个变量的数据类型，这样编译器才知道该分配多大的空间给它。以及它能够存储什么类型的数据。<br>在程序运行过程中，空间内的值是变化的，这个内存空间就被称为变量，而为了方便操作，给这个空间取个名字，即为变量名。变量的命名必须是合法的标识符，内存空间的值即为变量值，在声明变量时可以是剋有赋值，也可以赋初始值。</p>
</blockquote>
<p><img src="https://upload-images.jianshu.io/upload_images/8067684-f0a19c0aef1e07e6.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="2019-4-1-13.png"></p>
<p>系统的内存大致可以分为三个区域，系统区（os），程序区（program），数据区（data）。当程序执行时，程序代码加载到内存中的程序区，数据暂时储存在数据区中。<br>声明变量后，程序执行时，会在数据区配置空间给这两个变量。</p>
<ul>
<li><strong>常量的声明</strong></li>
</ul>
<blockquote>
<p>在程序运行过程中一直不会改变的量称常量，也称“final”变量。常量在整个程序中只能被赋值一次，在为所有的对象共享值时，常量时非常有用的。<br>在Java语言中声明一个常量，除了要指定数据类型外，还需要通过final关键字进行限定。</p>
</blockquote>
<p>final：最后，最终。<br>final关键字是一个非访问修饰符，final 表示”最后的、最终的”含义，变量一旦赋值后，不能被重新赋值。被 final 修饰的实例变量必须显式指定初始值。<br>final 修饰符通常和 static 修饰符一起使用来创建类常量。</p>
<p><a href="https://www.jianshu.com/p/915489eb0986" target="_blank" rel="noopener">关于java 修饰符</a></p>
<hr>
<ul>
<li><strong>变量的有效范围</strong></li>
</ul>
<blockquote>
<p>由于变量是被定义出来后暂存在内存中，所以等程序执行到某一点，该变量会被释放掉，也就是说变量是有生命周期的。因此，变量的有效范围是指程序代码访问该变量的区域。若超出该区域，则无法访问该变量。</p>
</blockquote>
<p><strong>在程序中，一般会根据变量的有效范围将变量分为成员变量和局部变量。</strong></p>
<ul>
<li>成员变量<blockquote>
<p>在类体中所定义的变量被称为成员变量，成员变量在整个类体中都有效，类的成员变量又可分为两种，<strong>静态变量和实例变量</strong>。</p>
</blockquote>
</li>
</ul>
<p><em>静态变量，需要使用static修饰符。静态变量的有效范围是可以跨类的，甚至可以达到整个程序之内，静态变量除了可以在本类调用，还可以以类名.变量名在其他类调用。</em></p>
<ul>
<li>局部变量</li>
</ul>
<blockquote>
<p>在类的方法体中定义的变量称为局部变量。局部变量只在当前代码块中有效。在类的方法中声明的变量，包括方法的参数都属于局部变量。局部变量只在当前定义的方法内有效，不能用于类的其他方法中。局部变量的生命周期取决于方法，当方法被调用的时候，JVM虚拟机就会分配内存空间。当方法结束，则释放方法中局部变量的占用的空间，局部变量也会被销毁。</p>
</blockquote>
<p><img src="https://upload-images.jianshu.io/upload_images/8067684-945342cce57e417b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="2019-4-1-14.png"></p>
<hr>
<ul>
<li><p>###运算符</p>
<blockquote>
<p>运算符是一些特殊的符号，主要用于数学函数，一些类型的赋值语句和逻辑比较的方面。Java中提供了丰富的运算符，赋值运算符，算数运算符，比较运算符等。</p>
</blockquote>
</li>
<li><p><strong>赋值运算符</strong></p>
</li>
</ul>
<blockquote>
<p>赋值运算符以=表示，他是一个二元运算符（对两个操作数处理），其功能是将右边的操作数的值赋给左边的操作数。</p>
</blockquote>
<p><strong>赋值运算符的运算规则是从右往左。</strong><br>在Java中赋值运算符是可以连起来使用的。</p>
<ul>
<li><strong>算数运算符</strong><blockquote>
<p>Java中的算术运算符主要又+，-，*，/，%。他们都是二元运算符。</p>
</blockquote>
</li>
</ul>
<p><img src="https://upload-images.jianshu.io/upload_images/8067684-01f69c794db5c146.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="2019-4-1-15.png"></p>
<ul>
<li><strong>自增自减运算符</strong></li>
</ul>
<blockquote>
<p>自增，自减运算符是单目运算符，可以放在操作数的前面，也可以放在操作数之后，操作元必须是一个整形或浮点型变量。自增自减的作用就是使变量自增1或自减1。</p>
</blockquote>
<p><strong>当自增自减运算符放在操作数前面时，表示，先使操作数加1在进行运算，放在后面则是先进行表达式的运算，再加减1</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">++a; //先加1</span><br><span class="line">a++;//后加1</span><br></pre></td></tr></table></figure>
<ul>
<li><strong>比较运算符</strong><blockquote>
<p>比较运算符属于二元运算符，用于出程序中的变量之间，变量和自变量之间以及其他类型的信息之间的比较。比较运算符的结构是boolean型。当结果成立，为true，否则为false。所有比较运算符通常作为判断依据使用在条件语句中。</p>
</blockquote>
</li>
</ul>
<p><img src="https://upload-images.jianshu.io/upload_images/8067684-94be843e28806342.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="2019-4-1-16.png"></p>
<ul>
<li><p><strong>逻辑运算符</strong></p>
<blockquote>
<p>返回类型为布尔值的表达式，如比较运算符，可以被组合在译器构成一个更加复杂的表达式。这是通过逻辑运算符来实现的。逻辑运算符包括&amp;&amp;（逻辑与），||（逻辑或），！（逻辑非），其中只有逻辑非是一元运算符。</p>
</blockquote>
<p>逻辑运算符的用法和含义：</p>
</li>
</ul>
<p><img src="https://upload-images.jianshu.io/upload_images/8067684-9260a0313629104f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="2019-4-1-17.png"></p>
<table>
<thead>
<tr>
<th style="text-align:center">表达式1</th>
<th style="text-align:center">表达式2</th>
<th style="text-align:center">1&amp;&amp;2</th>
<th style="text-align:center">1II 2</th>
<th style="text-align:center">!1</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center">true</td>
<td style="text-align:center">true</td>
<td style="text-align:center">true</td>
<td style="text-align:center">true</td>
<td style="text-align:center">false</td>
</tr>
<tr>
<td style="text-align:center">ture</td>
<td style="text-align:center">false</td>
<td style="text-align:center">false</td>
<td style="text-align:center">true</td>
<td style="text-align:center">false</td>
</tr>
<tr>
<td style="text-align:center">false</td>
<td style="text-align:center">false</td>
<td style="text-align:center">false</td>
<td style="text-align:center">false</td>
<td style="text-align:center">true</td>
</tr>
<tr>
<td style="text-align:center">false</td>
<td style="text-align:center">true</td>
<td style="text-align:center">false</td>
<td style="text-align:center">true</td>
<td style="text-align:center">true</td>
</tr>
</tbody>
</table>
<ul>
<li><p><strong>位运算符</strong></p>
<blockquote>
<p>位运算符除<strong>按位与</strong>和<strong>按位或</strong>外，其他只能用于处理整数的操作数。位运算是完全针对为方面的操作，整型数据在内存以二进制表示。</p>
</blockquote>
</li>
<li><p>按位与</p>
<blockquote>
<p>按位与运算符位&amp;，是双目运算符，运算法则：<strong>如果两个整型数a，b，对应位都是1，则结果位才是1，否则为0。如果操作数精度不同，则结果的精度与精度高的相同。</strong></p>
</blockquote>
</li>
<li><p>按位或</p>
<blockquote>
<p>按位或运算符为|，是双目运算符，按位或运算法则：<strong>如果两个整型数据a，b对应都是0<br>则结果为才为0，否则为1。结果精度与操作数精度高的相同。</strong></p>
</blockquote>
</li>
</ul>
<p><img src="https://upload-images.jianshu.io/upload_images/8067684-8cafab8620d9d0de.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="2019-4-1-18.png"></p>
<ul>
<li>按位取反<blockquote>
<p>按位取反运算也称安位非运算，运算符为~，单目运算符，就是将操作数二进制的1改为0。</p>
</blockquote>
</li>
<li><p>按位异或</p>
<blockquote>
<p>按位异或运算表示^，为双目运算符，运算法则：当两个操作数的二进制表示不同时，结果为0，否则为1。精度取最高。</p>
</blockquote>
</li>
<li><p><strong>移位运算</strong></p>
<blockquote>
<p>除了上述运算符之外，还可以对数据按二进制进行移位操作。Java移位运算符有三种：&lt;&lt;左移，&gt;&gt;右移，&gt;&gt;&gt;，无符号右移。</p>
</blockquote>
</li>
</ul>
<p><img src="https://upload-images.jianshu.io/upload_images/8067684-4ef63c0d9b08b6f0.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="2019-4-1-19.png"></p>
<p>左移就是将运算符左边的二进制按照运算符右边的操作数指定的位数向左移动。右边移空的位置补0。右移则稍微复杂一些，当最高位为0时，右移空的位就填入0，如果最高位是1，右移空的位就填1。</p>
<p><img src="https://upload-images.jianshu.io/upload_images/8067684-a3c6c7827f85df27.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="2019-4-1-20.png"></p>
<p>而无符号右移，则是无论最高位是0还是1，左侧被移空的高位都填入0。</p>
<p><strong>移位运算符可以实现整数的乘除以2的n次方的效果，如y&lt;&lt;2与y*4相同，y&gt;&gt;1，就是y/2，左移就是乘，右移就是除。</strong></p>
<ul>
<li><strong>三元运算符</strong></li>
</ul>
<p>三元运算符的使用格式为：<br><code>条件式？值1：值2</code></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">boolean b=20&lt;30?true:false;</span><br></pre></td></tr></table></figure>
<p>三元运算符的规则是：若表达式的值为true，则整个表达式取值1，否则取值2。<br>三元运算符等价于if else语句。</p>
<ul>
<li><strong>运算符的优先级</strong></li>
</ul>
<p>Java表达式就是使用运算符连接起来的符合Java规则的式子，运算符中运算的先后顺序。通常优先级由高到低的顺序依次是：<br>增量与减量运算，算数运算，比较运算，逻辑运算，赋值运算。<br>如果两个式子有同样的优先级，则左边的表达式要比右边的表达式先被处理。</p>
<p><img src="https://upload-images.jianshu.io/upload_images/8067684-626779d391653b0c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="2019-4-1-21.png"></p>
<hr>
<ul>
<li>###数据转换</li>
</ul>
<blockquote>
<p>类型的数据转换是将一个值从一种类型更改为另一种类型的过程，例如，可以将String类型“456”转换为一个数值型，而且可以将任意类型的数据转换为String型。</p>
</blockquote>
<p><strong>如果从低精度向高精度转换，则不会溢出，并且总是成功的，如果从高精度向低精度转换，则必然伴随着信息的缺失，有可能失败。</strong></p>
<ul>
<li>隐式类型转换<br>从低级类型向高级类型的转换，系统将自动进行，这种类型转换称为隐式类型转换。</li>
</ul>
<p>基本类型精度高低：byte&lt;short&lt;int&lt;long&lt;float&lt;double.<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">int x=34;</span><br><span class="line">flaot y=x; // 这就是一种隐式类型转换，</span><br></pre></td></tr></table></figure></p>
<ul>
<li>显示类型转换<br>当高精度的变量的值赋给低精度的变量时，必须使用显示类型转换（即强制类型转换）。</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">int a=(int)34.13;</span><br><span class="line">long y=(long)456.6f;</span><br><span class="line">int b=(int)&apos;d&apos;;</span><br></pre></td></tr></table></figure>
<p>当执行显示类型转换时，可能会导致精度的丢失。只要时Boolean型以外的其他类型之间的转换，全部都能以显示类型转换方法得到。</p>
<hr>
<p>Java语言基础 完。<br>更新时间：<br>2019-4-1<br>19：51</p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>你现在可以打赏本宝宝啦！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/weixing.png" alt="葛木小舍先生 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/zhifubao.png" alt="葛木小舍先生 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/gmxs/tags/java/" rel="tag"># java</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/gmxs/2019/03/28/java初探/java简介相关/" rel="next" title="Java简介相关">
                <i class="fa fa-chevron-left"></i> Java简介相关
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/gmxs/2019/04/01/技术总结集/关于环境变量的配置/" rel="prev" title="关于环境变量与环境变量的配置">
                关于环境变量与环境变量的配置 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zNTg1Ni8xMjM5Mg=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/gmxs/images/touxiang.png"
                alt="葛木小舍先生" />
            
              <p class="site-author-name" itemprop="name">葛木小舍先生</p>
              <p class="site-description motion-element" itemprop="description">不管过去过的如何，现在活的如何，将来将会如何。努力做好自己，朝梦想中的自己努力前进。</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/gmxs/archives/">
              
                  <span class="site-state-item-count">61</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/gmxs/categories/index.html">
                  <span class="site-state-item-count">20</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/gmxs/tags/index.html">
                  <span class="site-state-item-count">25</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/gmxs/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/gemuxiaoshe" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:MaYaPeng2017@outlook.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://weibo.com/u/5967971229/home?wvr=5&sudaref=graph.qq.com" target="_blank" title="weibo">
                      
                        <i class="fa fa-fw fa-weibo"></i>weibo</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                个人收集站
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://gemumiaoshe.wordpress.com/" title="葛木小舍先生的小世界" target="_blank">葛木小舍先生的小世界</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.w3cschool.cn/html/" title="W3Cschool" target="_blank">W3Cschool</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.alloyteam.com/nav/" title="web前端导航" target="_blank">web前端导航</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.itcast.cn/" title="传智播客" target="_blank">传智播客</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://5sing.kugou.com/index.html" title="5sing" target="_blank">5sing</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.mikecrm.com/login.php?s=2&d=form.php#/list/" title="麦客CRM" target="_blank">麦客CRM</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.51cto.com/" title="51CTO" target="_blank">51CTO</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#Java语言基础的大致组成"><span class="nav-number">1.</span> <span class="nav-text">Java语言基础的大致组成</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">葛木小舍先生</span>

  
</div>


<div class="powered-by">
<i class="fa fa-user-md"></i><span id="busuanzi_container_site_uv">
  本站访客数:<span id="busuanzi_value_site_uv"></span>
</span>
</div>



  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Mist</a> v5.1.4</div>




<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共111.1k字</span>
</div>

        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/gmxs/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/gmxs/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/gmxs/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/gmxs/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/gmxs/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/gmxs/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/gmxs/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/gmxs/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/gmxs/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/gmxs/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/gmxs/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/gmxs/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/gmxs/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("", "");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

</body>
</html>
